package cn.damai.controller.web;


import cn.damai.config.AlipayConfig;
import cn.damai.model.Order;
import cn.damai.order.service.OrderService;
import cn.damai.util.DubboUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("alipay")
public class AlipayController {

    @Reference(url = DubboUtil.ORDER_URL,version = DubboUtil.VRESION,group = DubboUtil.GROUP)
    private OrderService orderService;

    // 获取配置文件的信息
    private String app_id = AlipayConfig.app_id;
    private String private_key = AlipayConfig.private_key;
    private String notify_url = AlipayConfig.notify_url;
    private String return_url = AlipayConfig.return_url;
    private String url = AlipayConfig.url;
    private String charset = AlipayConfig.charset;
    private String format = AlipayConfig.format;
    private String public_key = AlipayConfig.public_key;
    private String sign_type = AlipayConfig.sign_type;

    /**
     * 支付请求
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/pay")
    public void pay(HttpServletRequest request, HttpServletResponse response, Order order) throws Exception {

        // 封装请求客户端
        AlipayClient client = new DefaultAlipayClient(url, app_id, private_key, format, charset, public_key, sign_type);

        // 支付请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrderNo();
        //付款金额，必填
        String total_amount = order.getTotalAmount() + "";
        //订单名称，必填
        String subject = order.getItemName();
        //商品描述，可空
//        String body = param.getRemark();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
//                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String form = client.pageExecute(alipayRequest).getBody(); // 生成表单

        response.setContentType("text/html;charset=" + charset);
        response.getWriter().write(form); // 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 同步跳转
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam("out_trade_no")String orderNo,
                            @RequestParam("trade_no")String tradeNo,
                            @RequestParam("total_amount")BigDecimal totalAmount,
                            Model model) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean signVerified = AlipaySignature.rsaCheckV1(params, public_key, charset, sign_type);

        if(signVerified) {

            Order order = orderService.queryOrderByOrderNo(orderNo);
            if(order == null){
                model.addAttribute("payMsg","商户订单号不存在!");
            }else {
                if(order.getTotalAmount().equals(totalAmount)){
                    model.addAttribute("payMsg","付款金额不对!");
                    return "user/payMsg";
                }

                if(order.getOrderType() == 2){
                    model.addAttribute("payMsg","当前订单已支付!");
                }else {
                    order.setOrderType(2);
                    order.setAliTradeNo(tradeNo);
                    order.setUpdatedTime(new Date());
                    orderService.updateOrder(order);
                    model.addAttribute("payMsg","支付成功,正为您转至订单页面!");
                }

            }


        }else{
            model.addAttribute("payMsg","支付失败!");
        }

        return "user/payMsg";
    }

    /**
     * 支付宝服务器异步通知
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request) throws Exception {
//        // 获取支付宝GET过来反馈信息
//        Map<String, String> params = new HashMap<String, String>();
//        Map<String, String[]> requestParams = request.getParameterMap();
//        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
//            }
//            params.put(name, valueStr);
//        }
//
//        boolean signVerified = AlipaySignature.rsaCheckV1(params, public_key, charset, signtype); // 调用SDK验证签名
//
//        if (signVerified) { // 验证成功 更新订单信息
//            System.out.println("异步通知成功");
//            // 商户订单号
//            String out_trade_no = request.getParameter("out_trade_no");
//            // 交易状态
//            String trade_status = request.getParameter("trade_status");
//            // 修改数据库
//        } else {
//            System.out.println("异步通知失败");
//        }
    }


}
